namespace XEAS.Framework.Rss
{
    using System;
    using System.Collections.Generic;
    using System.Text;

    public class RssGenerator
    {
        private static void AddRssItems(StringBuilder stringBuilder, List<RssItem> rssItems)
        {
            foreach (RssItem item in rssItems)
            {
                stringBuilder.Append("<item>");
                stringBuilder.Append("<title><![CDATA[ ");
                stringBuilder.Append(item.Title);
                stringBuilder.Append(" ]]> </title>");
                stringBuilder.Append("<link><![CDATA[ ");
                stringBuilder.Append(item.Link);
                stringBuilder.Append(" ]]> </link>");
                if (item.IsPermaLink)
                {
                    stringBuilder.Append("<guid isPermaLink=\"true\"><![CDATA[ ");
                    stringBuilder.Append(item.Guide);
                    stringBuilder.Append(" ]]> </guid>");
                }
                else
                {
                    stringBuilder.Append("<guid isPermaLink=\"false\"><![CDATA[ ");
                    stringBuilder.Append(item.Guide);
                    stringBuilder.Append(" ]]> </guid>");
                }
                stringBuilder.Append("<description><![CDATA[ ");
                stringBuilder.Append(item.Description);
                stringBuilder.Append(" ]]> </description>");
                stringBuilder.Append("<pubDate>");
                stringBuilder.Append(item.PubDate.ToString("R"));
                stringBuilder.Append("</pubDate>");
                stringBuilder.Append("</item>");
            }
        }

        public static string GenerateRss(RssChannel channel, List<RssItem> rssItems)
        {
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            stringBuilder.Append("<rss version=\"2.0\"><channel>");
            stringBuilder.Append("<title><![CDATA[ ");
            stringBuilder.Append(channel.Title);
            stringBuilder.Append(" ]]> </title>");
            stringBuilder.Append("<link><![CDATA[ ");
            stringBuilder.Append(channel.Link);
            stringBuilder.Append(" ]]> </link>");
            stringBuilder.Append("<description><![CDATA[ ");
            stringBuilder.Append(channel.Description);
            stringBuilder.Append(" ]]> </description>");
            stringBuilder.Append("<ttl>");
            stringBuilder.Append(channel.Ttl);
            stringBuilder.Append("</ttl>");
            AddRssItems(stringBuilder, rssItems);
            stringBuilder.Append("</channel></rss>");
            return stringBuilder.ToString();
        }
    }
}

